<?php
/**
 * Created by PhpStorm.
 * User: koterwong
 * Date: 2017/8/29
 * Time: 17:53
 */

namespace app\api\controller;

use app\api\model\SmsModel;
use app\api\model\UserModel;
use think\Db;
use think\Validate;

class PublicController extends ApiBaseController
{
    //发送短信验证码
    public function sendCode()
    {
        $mobile = input('mobile');
        $type = input('type');

        if (empty($mobile)) {
            returnError(API_PARAM_ERROR, '手机号不能为空');
        }

        if (empty($type)) {
            returnError(API_PARAM_ERROR, '验证码类型不能为空');
        }

        isPhoneNum($mobile) or returnError(API_PARAM_ERROR, '请输入正确的手机号');

        in_array($type, ['register', 'forgotten']) or returnError(API_PARAM_ERROR, '验证码类型不正确');

        //检验一个ip是否频发短信
        $ip = $this->request->ip();
        $count = Db::name('sms')->where(['ip' => $ip])->whereTime('create_time', 'd')->count();
        if ($count > 50) {
            returnError(500, '请勿频繁发短信');
        }

        //查询用户信息
        $userInfo = Db::name('user')->where(['mobile' => $mobile])->find();
        if ($type == 'register') {
            if ($userInfo) {
                returnError(500, '用户已存在');
            }
        } else {
            if (!$userInfo) {
                returnError(500, '用户不存在');
            }
        }

        //发送短信
        $code = getRandCode();
        $result = model('sms')->sendCode($mobile, $code);
        $nowtime = time();
        if ($result == '0') {
            $data = array(
                'type' => $type,
                'mobile' => $mobile,
                'code' => $code,
                'status' => 0,
                'ip' => $ip,
                'expire_time' => $nowtime + 60 * 10,
                'create_time' => $nowtime,
            );
            Db::name('sms')->insert($data);
            if (APP_DEBUG) {
                returnData(200, '发送成功' . $code);
            } else {
                returnData(200, '发送成功');
            }
        } else {
            returnError(500);
        }
    }

    //登录
    public function login()
    {
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require|min:6|max:32'
        ]);
        $validate->message([
            'mobile.require' => '手机号不能为空',
            'password.require' => '密码不能为空',
            'password.max' => '密码不能超过32个字符',
            'password.min' => '密码不能小于6个字符',
        ]);
        $data = input('post.');
        if (!$validate->check($data)) {
            returnError(API_PARAM_ERROR, $validate->getError());
        }

        $user['mobile'] = $data['mobile'];
        $user['user_pass'] = $data['password'];

        isPhoneNum($user['mobile']) or returnError(API_PARAM_ERROR, '请输入正确的手机号');

        $userModel = new UserModel();
        $loginResult = $userModel->mobileLogin($user);

        if ($loginResult == 3) {
            returnError(500, '用户被禁用');
        } elseif ($loginResult == 2) {
            returnError(500, '用户不存在');
        } elseif ($loginResult == 1) {
            returnCommonError('密码错误');
        } else {   //登录成功
            $token = cmf_generate_user_token($loginResult['id'], 'app');

            $data = [
                'token' => $token,
                'mobile' => $loginResult['mobile'],
                'avatar' => $loginResult['avatar'],
                'user_nickname' => $loginResult['user_nickname'],
            ];

            returnData(API_SUCCESS, '登录成功', $data);
        }

        returnError();
    }

    //注册
    public function register()
    {
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require|min:6|max:32',
            'code' => 'require'
        ]);
        $validate->message([
            'mobile.require' => '手机号不能为空',
            'password.require' => '密码不能为空',
            'password.max' => '密码不能超过32个字符',
            'password.min' => '密码不能小于6个字符',
            'code.require' => '验证码不能为空'
        ]);
        $data = $this->request->post();
        if (!$validate->check($data)) {
            return returnData(API_PARAM_ERROR, $validate->getError());
        }

        isPhoneNum($data['mobile']) or returnError(API_PARAM_ERROR, '请输入正确的手机号');

        $smsModel = new SmsModel();
        $check_sms = $smsModel->checkSMS('register', $data['mobile'], $data['code']);
        if ($check_sms == -1) {
            returnError(500, '验证码已过期');
        } else if ($check_sms == 0) {
            returnError(500, '验证码不正确');
        }

        //输入正确注册
        $userModel = new UserModel();
        $result = $userModel->registerUser(['mobile' => $data['mobile'], 'user_pass' => $data['password']]);

        switch ($result) {
            case 0:
                return returnData(200, '注册成功');
                break;
            case 1:
                return returnData(500, '您的账户已注册过');
                break;
            case 2:
                return returnData(500, '您输入的账号格式错误');
                break;
            default :
                return returnData();
        }
    }

    //修改密码
    public function resetPwd()
    {
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require|min:6|max:32',
            'code' => 'require'
        ]);
        $validate->message([
            'mobile.require' => '手机号不能为空',
            'password.require' => '密码不能为空',
            'password.max' => '密码不能超过32个字符',
            'password.min' => '密码不能小于6个字符',
            'code.require' => '验证码不能为空'
        ]);
        $data = $this->request->post();
        if (!$validate->check($data)) {
            return returnData(API_PARAM_ERROR, $validate->getError());
        }

        isPhoneNum($data['mobile']) or returnError(API_PARAM_ERROR, '请输入正确的手机号');

        $smsModel = new SmsModel();
        $check_sms = $smsModel->checkSMS('forgotten', $data['mobile'], $data['code']);
        if ($check_sms == -1) {
            returnError(500, '验证码已过期');
        } else if ($check_sms == 0) {
            returnError(500, '验证码不正确');
        }

        $userModel = new UserModel();
        $result = $userModel->resetPwd([
            'mobile' => $data['mobile'],
            'user_pass' => $data['password'],
        ]);

        switch ($result) {
            case 0:
                returnData();
                break;
            case 1:
                returnCommonError('用户不存在');
                break;
            default :
                returnError();
        }
    }
}